package com.edu.netty.netty;

import cn.hutool.json.JSONUtil;
import com.edu.netty.common.KafkaSender;
import com.edu.netty.entity.MessageEntity;
import com.edu.netty.util.ContextHelper;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;


/**
 * <p>
 * 自定义接受处理类
 * </p>
 *
 * @author jpge
 * @since 2024-03-29
 */
@Slf4j
public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 单netty交互
//        channelReadOld(ctx, msg);
        channelReadKafka(ctx, msg);

    }

    public void channelReadOld(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        log.info("服务端接收: " + buf.toString(CharsetUtil.UTF_8));
        ctx.write(buf);
    }

    public void channelReadKafka(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 1. 接收数据
        ByteBuf buf = (ByteBuf) msg;
        if (buf.readableBytes() <= 0) { // 已读取完
            return;
        }

        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);

        String body = new String(req, CharsetUtil.UTF_8);
        log.info("报文内容: " + body);

        // 2. 转化数据
        // 3. 解析数据
        MessageEntity messageEntity = parseMessage(body);
        String toJsonStr = JSONUtil.toJsonStr(messageEntity);
        log.info("报文解析结果: " + toJsonStr);

        // 4. 发送到kafka队列
        KafkaSender kafkaSender = (KafkaSender) ContextHelper.getBean(KafkaSender.class);
        kafkaSender.send("TEST", toJsonStr);
        // 5. 向硬件返回响应字符串
        String resp = "SHT|true|\0";
        ByteBuf out = ctx.alloc().buffer();
        out.writeBytes(resp.getBytes(StandardCharsets.UTF_8));
        ctx.writeAndFlush(out);
        if (out != null) {
            out.resetReaderIndex();
        }

        // 释放资源
        ReferenceCountUtil.release(msg);
        buf.resetReaderIndex();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    /**
     * 将字符串转化为对象
     */
    private MessageEntity parseMessage(String body) {
        String[] split = body.split("\\|");
        MessageEntity messageEntity = new MessageEntity();

        messageEntity.setMetercode(split[1]);
        messageEntity.setTem(Integer.parseInt(split[2]));
        messageEntity.setHum(Integer.parseInt(split[3]));
        messageEntity.setState(Integer.parseInt(split[4]));
        messageEntity.setLon(split[5]);
        messageEntity.setLat(split[6]);
        messageEntity.setCurtime(split[7]);

        return messageEntity;

    }

}
